package com.hmall.trade.listener;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.api.client.ItemFeign;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.cart.service.ICartService;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Wrapper;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class PayStatusListener {

    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private ItemFeign itemFeign;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("trade.pay.success.queue"),
            exchange = @Exchange(name = "hm.direct"),
            key = {"pay.success"}
    ))
    public void listenPaySuccess(Long OrderId) {
        iOrderService.markOrderPaySuccess(OrderId);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("order.queue"),
            exchange = @Exchange(name = "daley.direct", delayed = "true"),
            key = {"cancle"}
    ))
    public void cancleOrder(String orderSku) {
        String[] split = orderSku.split("-");
        Long orderId = Long.valueOf(split[1]);
        List<OrderDetailDTO> detailDTOS = JSONUtil.toList(split[0], OrderDetailDTO.class);

        Order order = iOrderService.getById(orderId);
        if (order.getStatus() != 1){
            return;
        }

        //取消订单
        iOrderService.update(Wrappers.<Order>lambdaUpdate()
                .set(Order::getStatus, 5)
                .eq(Order::getId, orderId));
        //恢复库存
        itemFeign.recoverStock(detailDTOS);
    }
}
